<template>
	<view class="room-bg" :style="{'background-image':'url('+baseUrl + liveBg + ')',backgroundSize:'cover'}">
		<view id="video-container" class="video-container" @click="like"></view>
		<view v-if="!isPush" class="pusher-setting">
			<pusher-setting @getPushInfo="getPushInfo" @startLive="createLive" @transCamera="transCamera">
			</pusher-setting>
		</view>
		<view v-else class="room-content">
			<!-- 头部 start -->
			<room-header
				:onlineUser="onlineUser" 
				:anchorInfo="userInfo" 
				:onlineUserNum="onlineUserNum" 
				:likeNum="likeNum" 
				@show-online-user="showOnlineUser">
			</room-header>
			<!-- 头部 end -->
			<!-- 聊天室 start -->
			<chatroom class="chatroom" :message="messageQueen"></chatroom>
			<!-- 聊天室 end -->
			<!-- 底部 -->
			<room-bottom class="room-bottom" @send-message="sendTextMessage" :isTimReady="isIMSDKReady" isPusher="true"
				@quitGroup="quitGroup" @like="like">
			</room-bottom>
			<!-- 底部 -->
			<!-- 礼物以及动画 start -->
			<gift-animation v-if="hasGift" class="gift-animation" @hideGiftAni="hideGiftAni" :sendUser="sendGiftUser" :giftInfo="giftInfo"></gift-animation>
			<!-- 礼物以及动画 end -->
			<!-- 在线用户卡片 start -->
			<view v-if="isShowOnlineUser" :animation="animation4" class="online-user">
				<online-user @hide-online-user="hideOnlineUser" 
					@getOnlineUser="getOnlineUser" 
					:loadingType="onlineUserLoadingType"
					:onlineUser="onlineUser">
				</online-user>
			</view>
			<!-- 在线用户卡片 end -->
			<!-- 主播端start -->
			<view v-if="isAnchor" class="btn-wraper">
				<view>
					<u-icon @click="transCamera" label="翻转" label-pos="bottom" label-color="#fff"
						name="../static/images/live/camera-reverse.png" size="48"></u-icon>
				</view>
				<!-- <view class="u-m-t-30">
					<u-icon label="美颜" label-pos="bottom" label-color="#fff"
						name="../static/images/live/beauty-face-white.png" size="48"></u-icon>
				</view> -->
			</view>
			<!-- 主播端end -->
		</view>
	</view>
</template>

<script>
	let setting = uni.getStorageSync('setting');

	import pusherSetting from './components/pusher-setting.vue'
	import roomHeader from './components/header.vue'
	import roomBottom from './components/bottom.vue'
	import chatroom from './components/chatroom.vue'
	import onlineUser from './components/online-user.vue'
	import giftAnimation from './components/gift-animation.vue'
	import noOwner from './components/noowner.vue'
	import TRTC from 'trtc-js-sdk'
	import TWebLive from 'tweblive'
	import {
		mixinChat
	} from './mixins/chat.js';

	export default {
		mixins: [mixinChat],
		components: {
			pusherSetting,
			roomHeader,
			roomBottom,
			chatroom,
			onlineUser,
			giftAnimation,
			noOwner,
		},
		data() {
			return {
				baseUrl: this.config.baseUrl,
				liveBg: setting.live_room_bg,
				playUrl: {
					flv: '',
					cdnUrl: '',
				},
				isPush: false,
				pusher: null,
				groupInfo: {},
				userInfo: {},
				userRole: 'pusher',
				chatInfo: {
					streamId: ''
				},
				pushInfo: {
					title: '',
					thumb: ''
				},
				isAnchor: true,
				anchorInfo: {},
				animation: null,
				animation2: null,
				animation3: null,
				animation4: null,
				animationUserCard: null,
				isShowUserCard: false,
				isShowOnlineUser: false,
				hasgift: false,
				giftAvatar: '',
				giftNick: '',
				hascoupon: false,
				giftStack: [],
				couponStack: [],
				goods: [],
				noticeText: '',
				roomStatus: '0',
				isShowIntroduction: false,
				giftList: [],
				cameraList: {},
				currentCameraId: '',
			}
		},
		computed: {},
		watch: {},
		methods: {
			init() {
				this.initChat();
				this.initPusher();
				this.getCameraList();
			},
			getCameraList() {
				this.pusher.getCameraList().then(devices => {
					this.cameraList = devices;
				});
			},
			transCamera() {
				this.currentCameraId = this.pusher.getCurrentCamera();
				this.cameraList.forEach(dev => {
					if (this.currentCameraId != dev.deviceId) {
						this.pusher.setCurrentCamera(dev.deviceId);
						//this.setRenderView(dev.deviceId);
					}
					console.log('camera label: ' + dev.label + ' deviceId: ' + dev.deviceId);
				});
			},
			createLive() {
				if (this.pushInfo.title == '') {
					this.$u.toast('请输入直播间标题');
					return false;
				}

				this.$u.post('live/api.live/createRoom', this.pushInfo).then(res => {
						this.chatInfo.groupId = res.data.roomid;
						this.chatInfo.streamId = res.data.stream_id;
						this.createRoom();
					})
					//.catch((error) => {
					//	console.error('createLive Error', error)
					//	this.$u.toast('直播间创建失败,请重试!');
					//	//this.$u.toast(error.msg);
					//})
			},
			createRoom() {
				this.im.createRoom({
					name: this.pushInfo.name,
					roomID: this.chatInfo.groupId
				}).then((imResponse) => { // 创建成功
					console.log('createRoom 创建成功', roomID)
					this.enterRoom();
					this.startPush();
				}).catch((imError) => {
					// 10021:群组 ID 已被使用，请选择其他的群组 ID。
					// 10025:群组 ID 已被使用，并且操作者为群主，可以直接使用。
					if (imError.code === 10021 || imError.code === 10025) {
						this.enterRoom();
						this.startPush();
					}
				})
			},
			getPushInfo(info) {
				console.log('push info', info)
				this.pushInfo = info;
			},
			initPusher() {
				// 1、创建 Pusher（推流）对象
				this.pusher = TWebLive.createPusher({
					userID: this.chatInfo.userID
				});
				// 2、设置渲染界面，且从麦克风采集音频，从摄像头采集视频（默认720p）
				setTimeout(() => {
					this.setRenderView();
				}, 1000)

				this.pusher.on(TWebLive.EVENT.RTC_CONNECTION_STATE_CHANGED, this.onRTCConnectionStateChanged)
				this.pusher.on(TWebLive.EVENT.RTC_CLIENT_BANNED, this.onRTCClientBanned)
				this.pusher.on(TWebLive.EVENT.RTC_CLIENT_ERROR, this.onRTCError)
			},
			setRenderView() {
				this.pusher.setRenderView({
					elementID: 'video-container',
					audio: true,
					video: true
				}).then(() => {
					// 设置背景
					let el = window.document.getElementById('video-container').childNodes;
					el[0].style.backgroundColor = 'rgba(0,0,0,0)';
					console.log('pusher | setRenderView | success');
				}).catch(error => {
					console.error('pusher | setRenderView | failed', error);
				});

			},
			onRTCConnectionStateChanged(event) {
				console.log('demo pusher | onRTCConnectionStateChanged |', event)
			},
			onRTCClientBanned(event) {
				console.log('demo pusher | onRTCClientBanned |', event)
			},
			onRTCError(event) {
				console.log('demo pusher | onRTCError |', event)
			},
			//推流
			startPush() {
				let SDKAppID = this.chatInfo.SDKAppID;
				let userID = this.chatInfo.userID;
				let userSig = this.chatInfo.userSig;
				let liveDomainName = this.chatInfo.liveDomainName;
				let groupId = this.chatInfo.groupId;
				let streamID = this.chatInfo.streamId;
				//let streamID = `${SDKAppID}_${this.chatInfo.groupId}_${userID}_main` //sdkappid_roomid_userid_main
				let url =
					`room://livedomainname=${liveDomainName}&sdkappid=${SDKAppID}&roomid=${groupId}&userid=${userID}&usersig=${userSig}&streamid=${streamID}`;
				this.pusher.startPush(url).then(() => {
					this.isPush = true
					this.getLiveStreamURL()
					uni.showToast({
						title: '直播已开启哦~'
					})

				}).catch((error) => {
					uni.showToast({
						title: '推流失败，请重试哦~',
						icon: 'none'
					})
					console.error('startPush | failed', error)
				})
			},
			// 获取推流地址
			getLiveStreamURL() {
				let url = this.pusher.getLiveStreamURL()
				let type = 'cdn';
				let userID = this.userInfo.user_id;
				let roomid = this.chatInfo.groupId; // + '0000000000000000000000000000';
				let title = this.pushInfo.title;
				this.playUrl.flv = url
				this.playUrl.cdnUrl = `${this.liveDomain}?type=${type}&anchorId=${userID}&roomid=${roomid}&title=${title}`
				console.log('demo pusher | getLiveStreamURL | ' + url, `cdn 观看：${this.playUrl.cdnUrl}`)
			},
			quitGroup() {
				let that = this;
				uni.showModal({
					content: '确定要关闭直播吗?',
					success(res) {
						if(res.confirm){
							that.closeLive();
						}
					}
				})
			},
			closeLive(){
				this.pusher.stopPush().then(() => {
					console.log('pusher | stopPush | ok');
					this.$u.post('live/api.live/endLive', {group_id: this.chatInfo.groupId}).then(res => {
							this.imStopPush();
						})
						.catch((error) => {
							console.error('endLive Error', error)
						})
				}).catch(error => {
					console.error('pusher | stopPush | failed', error);
				});
			},
			_formatNick(userID, nick) {
				if (userID === this.userInfo.userID) {
					return '我'
				}
				return nick
			},
			buy(data) {
				wx.showLoading()
				this.tls.buy(data).then(() => {
					wx.hideLoading()
					this.hidegoods()
				})
			},
			hideani() {
				this.hasgift = false,
					this.giftAvatar = '',
					this.giftNick = ''
				setTimeout(() => {
					var msg = this.giftStack.shift()
					if (msg) {
						this.hasgift = true,
							this.giftAvatar = msg.giftAvatar,
							this.giftNick = msg.giftNick
					}
				}, 1000)
			},
			showOnlineUser() {
				this.isShowOnlineUser = true
				setTimeout(() => {
					const ani = wx.createAnimation({
						duration: 200
					})

					ani.bottom(0).step()
					this.animation4 = ani.export()
				}, 0)
			},
			hideOnlineUser() {
				const duration = 200
				const ani = wx.createAnimation({
					duration
				})
				ani.bottom('-45vh').step()

				this.animation4 = ani.export()
				setTimeout(() => {
					this.isShowOnlineUser = false
				}, duration)
			},
			showUserCard({
				user_id
			}) {
				this.isShowUserCard = true
				this.userCardId = user_id
				setTimeout(() => {
					const ani = wx.createAnimation({
						duration: 200
					})
					ani.bottom(0).step()

					this.animationUserCard = ani.export()
				}, 0)

			},
			hideUserCard() {
				const duration = 200
				const ani = wx.createAnimation({
					duration
				})
				ani.bottom('-45vh').step()

				this.animationUserCard = ani.export()
				setTimeout(() => {
					this.isShowUserCard = false
				}, duration)
			},
			sendgift() {
				wx.showModal({
					title: '提示',
					content: '确认送礼？',
					success: async (data) => {
						try {
							if (data.confirm) {
								let msg = []
								msg.push({
									name: this._formatNick(9527, '土豪'),
									message: '给主播送礼了',
									id: `id${Date.now()}`
								})
								this.message = this.message.concat(msg)
								this.hasgift = true
								this.giftAvatar = this.config.baseUrl + '/gift-demo.png'
								this.giftNick = '土豪'

								//this.tls.sendGift('礼物')
							}
						} catch (e) {
							wx.showToast({
								title: e.message
							})
						} finally {
							this.hideGift();
						}
					}
				})
			},

			async like() {
				console.log('click like ');
				this.$refs.like.like();
				/* try {
					await Model.like({
						from_id: this.userInfo.userID,
						to_id: this.groupInfo.ownerID
					})
					this.tls.like()
				} catch (e) {
					uni.showToast({
						title: e.message,
						icon: 'none'
					})
					//wx.showToast({ title: e.message })
				} */
			},

			_getVarsByKey(arr, key) {
				var res
				for (var i = 0; i < arr.length; i++) {
					if (arr[i].key === key) {
						res = arr[i].value;
						break;
					}
				}
				return res
			},
			async getInfo() {
				this.$u.get('live/api.live/getInfo?role=live').then(res => {
					this.chatInfo = res.data.chatInfo;
					this.userInfo = res.data.userInfo;
					this.anchorInfo = res.data.anchorInfo;
					this.init();
				})
			},

		},

		async onLoad(data) {
			try {
				this.app.isLogin(this); //强制登陆
				this.getInfo()
			} catch (e) {
				console.warn(e)
			}

		},

	}
</script>

<style lang="scss" scoped>
	.room-bg {
		height: 100vh;
		width: 100vw;
		overflow: hidden;
		position: relative;
	}

	.bg-img {
		height: 100vh;
		width: 100vw;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 0;
	}

	.room-content {
		height: 100vh;
		width: 100vw;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 2;
	}

	.video-container {
		height: 100vh;
		width: 100vw;
		position: absolute;
		top: 0;
		left: 0;
	}

	.room-bottom {
		position: absolute;
		bottom: 0;
		width: 100vw;
		height: 50px;
		padding: 0 20rpx;
		margin-bottom: constant(safe-area-inset-bottom);
		/* 兼容 iOS < 11.2 */
		margin-bottom: env(safe-area-inset-bottom);
		/* 兼容 iOS >= 11.2 */
	}

	.chatroom {
		width: 60vw;
		max-height: 30vh;
		position: absolute;
		bottom: 120rpx;
		z-index: 100;
		padding: 20rpx;
		overflow: hidden;
	}

	.gifts,
	.goodslist,
	.introduction,
	.online-user,
	.user-card {
		position: absolute;
		width: 100vw;
		height: 45vh;
		bottom: -45vh;
		z-index: 800;
		left: 0;
	}

	.gifts {
		height: 620rpx;
		bottom: -620rpx;
	}

	.goodslist {
		height: 60vh;
		bottom: -60vh;
	}

	.user-card {
		background-color: unset;
	}

	.gift-animation {
		position: absolute;
		top: 30vh;
		left: 20rpx;
	}

	.coupon {
		margin-top: 400rpx;
	}

	.live-player {
		width: 100vh;
		height: 100vw;
		background-color: #fff;
	}

	.notice {
		position: absolute;
		left: 20rpx;
		bottom: 50vh;
		max-width: 60vw;
	}

	.like {
		position: absolute;
		right: 20rpx;
		bottom: 140rpx;
	}

	.btn-wraper {
		position: absolute;
		right: 20rpx;
		top: 200rpx;
	}
</style>
